package com.boot.down.service.impl;

import com.boot.down.entity.UserInfo;
import com.boot.down.exception.SecKillException;
import com.boot.down.mapper.UserInfoMapper;
import com.boot.down.service.UserInfoService;
import com.boot.down.util.redis.RedisLockMock;
import com.boot.down.vo.UserVO;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Administrator
 */
@Slf4j
@Service
@Transactional
public class UserInfoServiceImpl implements UserInfoService {

    private final long TIMEOUT = 10 * 1000L;

    @Autowired
    private RedisLockMock redisLock;

    @Resource
    private UserInfoMapper userInfoMapper;

    @CachePut(value = "userVos",key = "'userAll'")
    @Override
    public List<UserVO> selectAll() {
        List<UserInfo> userInfoList = userInfoMapper.queryAllSortByCreateTime();
        List<UserVO> userVOList = Lists.newArrayList();
        UserVO userVO;
        if(!CollectionUtils.isEmpty(userInfoList)){
            for(UserInfo userInfo : userInfoList){
                userVO = new UserVO();
                userVO.setUserName(userInfo.getUserName())
                        .setUserIdCard(userInfo.getUserIdCard())
                        .setUserRole(userInfo.getUserRole())
                        .setCreateTime(userInfo.getCreateTime());
                userVOList.add(userVO);
            }
            return userVOList;
        }
        return null;
    }

    @Cacheable(value = "UserInfo", key = "'name_'+#userName+'passwd_'+#password")
    @Override
    public UserInfo login(String userName, String password) {

        return  userInfoMapper.login(userName, password);
    }

    @Override
    public String addUserInfo(String userName) {

        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(userName);
        userInfo.setUserIdCard("123456789");
        userInfo.setUserPwd("123456");
        userInfo.setUserImg("http://www.baidu.com");
        userInfo.setUserRole("小王");
        //加锁
        long time = System.currentTimeMillis() + TIMEOUT;
        if(!redisLock.lock(userName,String.valueOf(time))){
            throw new SecKillException(101, "人太多了, 换个姿势");
        }
        int count = userInfoMapper.insertUserInfo(userInfo);
        //解锁
        redisLock.unlock(userName, String.valueOf(time));
        return count+"印象行数";
    }
}